<template>
    <div class="exam-process" :class="{ 'is-mobile': $isMobile }">
        <div class="exam-header">考试进度</div>

        <div class="mobile-exam" v-if="$isMobile">
            <div class="calcTime">{{ formattedTime }}</div>
            <div class="submit__btn" @click="submitAnswers">交卷</div>
        </div>

        <div class="exam-process__content" v-loading="loading">
            <div class="exam-process__content__left" v-if="!$isMobile">
                <menu-card :datas="exams" :userAnswers="userAnswers" type="process" @itemClick="itemClick"
                    :activeIndex="activeIndex">
                    <div class="exam-submit">
                        <div class="exam-submit__time">
                            <div class="calcTime">{{ formattedTime }}</div>
                            <div class="iconfont" :class="{ 'pauseStatus': pauseStatus }"></div>
                        </div>
                        <div class="submit__btn" @click="submitAnswers">交卷</div>
                    </div>
                </menu-card>
            </div>



            <div class="exam-process__content__right">
                <question-list :datas="exams" :userAnswers="userAnswers" @itemClick="itemClick" type="process"
                    :activeIndex="activeIndex" />
            </div>
        </div>
    </div>
</template>


<script>
import menuCard from "./components/menu-card.vue"
import questionList from "./components/list.vue"
import { calcInitUserList, formatExams } from "./calc";
export default {
    components: {
        menuCard,
        questionList,
    },

    data() {
        return {
            activeIndex: 0,
            loading: false,
            exams: [],
            pauseStatus: false,
            userAnswers: [],
            remainingTime: 0,
            countdownInterval: null,

        }

    },

    computed: {
        formattedTime() {
            const minutes = Math.floor(this.remainingTime / 60);
            const seconds = this.remainingTime % 60;
            return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
    },


    mounted() {
        this.getDatas();
    },
    beforeDestroy() {
        clearInterval(this.countdownInterval)
    },

    methods: {


        async getDatas() {
            const loading = this.$loading();
            const { examId } = this.$route.query;
            let { data } = await this.$fetch.get(`/api/topic-lesson-exams/get`, { id: examId });
            loading.close()

            let { exams, answers } = formatExams(data)
            this.exams = exams;
            this.userAnswers = calcInitUserList(exams);
            if (answers && answers.length) {
                return this.$router.replace({
                    name: "lesson-exam-detail",
                    query: {
                        examId,
                    }
                })
            }
            this.startCountdown(60);

        },

        tooglePause() {
            if (this.pauseStatus) {
                this.countdownInterval = setInterval(() => {
                    if (this.remainingTime > 0) {
                        this.remainingTime--;
                    } else {
                        this.stopCountdown();
                    }
                }, 1000);
            } else {
                clearInterval(this.countdownInterval);
            }
            this.pauseStatus = !this.pauseStatus;
        },

        startCountdown(minutes) {
            this.remainingTime = minutes * 60; // convert minutes to seconds
            this.countdownInterval = setInterval(() => {
                if (this.remainingTime > 0) {
                    this.remainingTime--;
                } else {
                    this.stopCountdown();
                }
            }, 1000);
        },
        stopCountdown() {
            this.pauseStatus = true;
            clearInterval(this.countdownInterval);
            this.countdownInterval = null;
            this.endExam()

        },

        submitAnswers() {
            this.endExam()
        },

        async endExam() {
            const { examId } = this.$route.query;
            let { data: { examsResult } } = await this.$fetch.post(`/api/topic-lesson/endExam`, { examId, answers: this.userAnswers });

            if (examsResult.status) {
                this.$alert('查看考试结果', "恭喜您，考试通过", {
                    confirmButtonText: '确定',
                    showClose: false,
                    showCancelButton: false,
                    center: true,
                    customClass: this.$isMobile ? "exam-result-alert-mobile" : "", callback: async () => {
                        this.$router.push({
                            name: "lesson-exam-result",
                            query: {
                                examId,
                            }
                        })
                    }
                })
            } else {
                this.$alert('查看考试结果', "考试已结束，您未通过考试，请再接再厉~", {
                    confirmButtonText: '确定',
                    showClose: false,
                    showCancelButton: false,
                    center: true,
                    customClass: this.$isMobile ? "exam-result-alert-mobile" : "",
                    callback: async () => {
                        this.$router.push({
                            name: "lesson-exam-result",
                            query: {
                                examId,
                            }
                        })
                    }
                })
            }
        },



        itemClick(index) {
            this.activeIndex = index;
            const targetElement = document.querySelector(`.exam-question-${index + 1}`);
            const parentElement = document.querySelector(".exam-process__content__right")


            if (targetElement && parentElement) {
                const targetTop = targetElement.offsetTop;
                const parentTop = parentElement.offsetTop;
                const relativeTop = targetTop - parentTop;


                parentElement.scrollTo({
                    top: relativeTop,
                    left: 0,
                    behavior: 'smooth'
                });
            }



        },



    },


}
</script>


<style lang="less" scoped>
.exam-process {
    background: #FFFFFF;
    width: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    height: calc(100vh - 200px);

    .exam-header {
        padding-top: 22px;
        padding-bottom: 19px;
        padding-left: 30px;
        font-family: PingFangSC, PingFang SC;
        font-weight: bolder;
        font-size: 22px;
        color: #333333;
        line-height: 30px;
        text-align: left;
        font-style: normal;
        border: 0.5px solid #EFEFEF;
    }

    .exam-process__content {
        display: flex;
        flex: 1;
        flex-direction: row;
        flex-wrap: nowrap;
        height: 100%;
        overflow: hidden;

        .exam-process__content__left {
            width: 252px;
            background: #F8F9FB;
            border-right: 1px solid #EFEFEF;
        }

        .exam-process__content__right {
            background: #fff;
            margin: 30px 30px 30px 60px;
            flex: 1;
            overflow-y: auto;
        }
    }
}

.exam-submit {
    background: #F8F9FB;
    padding-top: 24px;
    padding-bottom: 21px;

    .exam-submit__time {
        padding-left: 30px;
        display: flex;
        flex-direction: row;
        margin-bottom: 30px;

        .calcTime {
            font-family: PingFangSC, PingFang SC;
            font-weight: bolder;
            font-size: 22px;
            color: #333333;
            line-height: 30px;
            height: 30px;
            text-align: left;
            font-style: normal;
            padding-right: 12px;
            border-right: 1px solid #D8D8D8;
        }

        .iconfont {
            width: 30px;
            height: 30px;
            margin-left: 15px;
            background: url(../../assets/pause.svg) no-repeat center center;
            background-size: 30px 30px;

            &.pauseStatus {
                background: url(../../assets/play-pause.svg) no-repeat center center;
                background-size: 30px 30px;

            }
        }



    }

    .submit__btn {
        background: #3560AB;
        border-radius: 8px;
        padding: 8px 0;
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 16px;
        color: #FFFFFF;
        line-height: 22px;
        text-align: center;
        font-style: normal;
        cursor: pointer;
    }

}

.exam-process.is-mobile {
    height: calc(100vh - 60px);


    .exam-header {
        padding: 10px;
        font-size: 18px;
        font-weight: bolder;
        line-height: 28px;
    }

    .mobile-exam {
        position: relative;
        left: 100vw;
        transform: translateX(calc(-100% - 10px));
        top: -40px;
        display: flex;
        width: max-content;
        height: 30px;
        display: flex;
        justify-content: center;
        align-items: center;

        .calcTime {
            color: #999;
        }

        .submit__btn {
            margin-left: 8px;
            background: #3560AB;
            padding: 4px 8px;
            width: 100%;
            border-radius: 4px;

            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 14px;
            color: #FFFFFF;
            line-height: 20px;
        }

    }

    .exam-process__content {
        display: flex;
        flex-direction: column;
        position: relative;
        overflow: hidden;


        .exam-process__content__right {
            margin: 10px;
            overflow-y: auto;
        }
    }


}
</style>


<style lang="less">
.exam-result-alert-mobile {
    width: 80vw;
}
</style>